package com.eightbears.beboy.ui.user.activity;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.eightbears.beboy.R;
import com.eightbears.beboy.adapter.LocationAddressAdapter;
import com.eightbears.beboy.base.BaseActivity;
import com.eightbears.beboy.base.cache.DistrictCache;
import com.eightbears.beboy.base.util.AMapUtil;
import com.eightbears.beboy.base.util.SPUtil;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.view.SwipeBackLayout;
import com.eightbears.beboy.base.view.layout.MyLinearLayoutManager;
import com.eightbears.greendao.District;
import com.socks.library.KLog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.eightbears.beboy.base.cache.DistrictCache.CODE_CITY;
import static com.eightbears.beboy.base.cache.DistrictCache.CODE_DISTRICT;
import static com.eightbears.beboy.base.cache.DistrictCache.CODE_PROVINCE;
import static com.eightbears.beboy.base.util.CommonAPI.delayMillis;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_ADDRESS;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_CITY;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_DISTRICT;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_LATITUDE;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_LONGITUDE;
import static com.eightbears.beboy.ui.user.activity.ShowLocationActivity.PARAMS_PROVINCE;

public class SelLocationActivity extends BaseActivity implements
        PoiSearch.OnPoiSearchListener, LocationSource, AMapLocationListener
        , GeocodeSearch.OnGeocodeSearchListener, AMap.OnCameraChangeListener
        , Inputtips.InputtipsListener, BaseQuickAdapter.RequestLoadMoreListener,
        SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.et_search)
    AutoCompleteTextView et_search;
    @BindView(R.id.mv_map)
    TextureMapView mapView;
    @BindView(R.id.swipeLayout)
    SwipeRefreshLayout swipeLayout;
    @BindView(R.id.rv_list)
    RecyclerView rv_list;
    @BindView(R.id.tv_submit)
    TextView tv_submit;
    @BindView(R.id.sw_finish)
    SwipeBackLayout sw_finish;


    private Handler handler = new Handler();

    // 地图
    private AMap aMap;  //地图对象
    private PoiSearch.Query poiQuery;
    private BitmapDescriptor movingDescriptor, chooseDescripter;
    private LocationSource.OnLocationChangedListener mListener;
    private AMapLocationClientOption mLocationOption;
    private AMapLocationClient mLocationClient;
    private LatLng location;
    private ValueAnimator animator;
    private Marker centerMarker;
    private LatLonPoint screenPoint;
    private PoiItem selPoiItem;
    private List<Tip> listInput;

    private String provinceId, cityId, districtId, fullAddress;
    private String provinceName, cityName, districtName, snippet;
    private int currentPage = 1;
    private int isEnd = 0;
    private boolean isMovingMarker = false, isSle = false;

    private LocationAddressAdapter locationAddressAdapter;
    private  Intent intent = new Intent();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sel_location);
        initView();
        initData();
        initEvent();
        initMap();
        mapView.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        ButterKnife.bind(this);
        initAdapter();
        et_search.setDropDownBackgroundResource(R.color.text_color_fff);
        tv_title.setText(R.string.text_sel_location);
        tv_submit.setVisibility(View.VISIBLE);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvent() {
        et_search.addTextChangedListener(searchLocation);
        locationAddressAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                selPoiItem = (PoiItem) adapter.getItem(position);
                switch (view.getId()) {
                    case R.id.ll_item_middle:
                        isSle = true;
                        LatLng latLng = new LatLng(selPoiItem.getLatLonPoint().getLatitude(),
                                selPoiItem.getLatLonPoint().getLongitude());
                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(latLng));
                        locationAddressAdapter.selItem(selPoiItem);
                        provinceName = selPoiItem.getProvinceName();
                        cityName = selPoiItem.getCityName();
                        districtName = selPoiItem.getAdName();
                        snippet = selPoiItem.getSnippet();
                        getLocationInfo();
                        break;
                }
            }
        });

        et_search.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                isSle = false;
                LatLonPoint point = listInput.get(position).getPoint();
                if(null != point) {
                    aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(point.getLatitude(), point.getLongitude())));
                    et_search.setText("");
                    locationAddressAdapter.selItem(null);
                } else {
                    ShowToast.showShortToast(getString(R.string.alert_address_error));
                }
            }
        });

        sw_finish.setCallBack(new SwipeBackLayout.CallBack() {
            @Override
            public void onFinish() {
                finish();
            }
        });
    }

    @OnClick(R.id.ll_back)
    void back() {
        finish();
    }

    @OnClick(R.id.tv_submit)
    void searchLocation() {
        if (isSle) {
            intent.putExtra(PARAMS_LATITUDE, screenPoint.getLatitude());
            intent.putExtra(PARAMS_LONGITUDE, screenPoint.getLongitude());
            intent.putExtra(PARAMS_ADDRESS, fullAddress);
            intent.putExtra(PARAMS_PROVINCE, provinceId);
            intent.putExtra(PARAMS_CITY, cityId);
            intent.putExtra(PARAMS_DISTRICT, districtId);
            KLog.e(screenPoint.getLatitude());
            setResult(RESULT_OK, intent);
            finish();
        } else {
            ShowToast.showShortToast(getString(R.string.text_sel_address));
        }
    }

    private void doSearchQuery() {
        String searchContent = "";
        poiQuery = new PoiSearch.Query(searchContent, "", SPUtil.getUserLocation().getCityName());
        poiQuery.setPageSize(20);
        poiQuery.setPageNum(currentPage);
        poiQuery.setCityLimit(true);
        PoiSearch poiSearch = new PoiSearch(this, poiQuery);
        poiSearch.setBound(new PoiSearch.SearchBound(screenPoint, 1000, true));
        poiSearch.setOnPoiSearchListener(this);
        poiSearch.searchPOIAsyn();
    }

    /**
     * 初始化高德地图
     */
    private void initMap() {
        // 初始化地图变量
        if (aMap == null) {
            aMap = mapView.getMap();
        }
        aMap.setLocationSource(this);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        movingDescriptor = BitmapDescriptorFactory
                .fromResource(R.mipmap.location_moving);
        chooseDescripter = BitmapDescriptorFactory
                .fromResource(R.mipmap.location_moving);
        GeocodeSearch geocodeSearch = new GeocodeSearch(this);
        geocodeSearch.setOnGeocodeSearchListener(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);
        aMap.setMyLocationEnabled(true);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setOnCameraChangeListener(this);
        fixedMarker();
        setUpLocationStyle();
    }

    private void setUpLocationStyle() {
        // 自定义系统定位蓝点
        MyLocationStyle myLocationStyle = new MyLocationStyle();
        myLocationStyle.myLocationIcon(BitmapDescriptorFactory
                .fromResource(R.mipmap.icon_gps));
        myLocationStyle.strokeWidth(1);
        myLocationStyle.radiusFillColor(Color.TRANSPARENT);
        aMap.setMyLocationStyle(myLocationStyle);
    }


    private void getLocationInfo() {
        District province = DistrictCache.getInstance(this)
                .getCacheByName(provinceName, CODE_PROVINCE);
        District city = DistrictCache.getInstance(this)
                .getCacheByName(cityName, CODE_CITY);
        District district = DistrictCache.getInstance(this)
                .getCacheByName(districtName, CODE_DISTRICT, city.getId());

        provinceId = province.getId();
        cityId = city.getId();
        districtId = district.getId();

        fullAddress = province.getName() + city.getName() + district.getName() + snippet;


    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                location = new LatLng(aMapLocation.getLatitude(), aMapLocation.getLongitude());
                screenPoint = new LatLonPoint(location.latitude, location.longitude);
                mListener.onLocationChanged(aMapLocation);
                provinceName = aMapLocation.getProvince();
                cityName = aMapLocation.getCity();
                districtName = aMapLocation.getDistrict();
                snippet = aMapLocation.getStreetNum();
                getLocationInfo();
                animMarker();
            } else {
                ShowToast.showShortToast(getString(R.string.text_location_error));
            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        mListener = onLocationChangedListener;
        if (mLocationOption == null) {
            mLocationClient = new AMapLocationClient(SelLocationActivity.this);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mLocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setInterval(6000 * 10 * 5);
            mLocationClient.setLocationOption(mLocationOption);
            mLocationClient.startLocation();
        }
    }


    @Override
    public void deactivate() {
        mListener = null;
        if (mLocationOption != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }


    private void animMarker() {
        isMovingMarker = false;
        if (animator != null) {
            animator.start();
            return;
        }
        animator = ValueAnimator.ofFloat(mapView.getHeight() / 2, mapView.getHeight() / 2 - 50);
        animator.setInterpolator(new DecelerateInterpolator());
        animator.setDuration(300);
        animator.setRepeatCount(1);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                Float value = (Float) animation.getAnimatedValue();
                centerMarker.setPositionByPixels(mapView.getWidth() / 2, Math.round(value));
            }
        });
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                centerMarker.setIcon(chooseDescripter);
            }
        });
        animator.start();
    }

    private void endAnim() {
        if (animator != null && animator.isRunning())
            animator.end();
    }

    /**
     * 固定大头针
     */
    private void fixedMarker() {
        MarkerOptions centerMarkerOption = new MarkerOptions().position(location).icon(chooseDescripter);
        centerMarker = aMap.addMarker(centerMarkerOption);
        centerMarker.setPositionByPixels(mapView.getWidth() / 2,
                mapView.getHeight() / 2);
        //主线称
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                CameraUpdate update = CameraUpdateFactory.zoomTo(17);
                //在指定的持续时间内，动画地移动地图到指定的位置，完成时调用可选的回调方法。
                aMap.animateCamera(update, 1000, new AMap.CancelableCallback() {
                    @Override
                    public void onFinish() {
                        //设置一个可视范围变化时的回调的接口方法。
                        aMap.setOnCameraChangeListener((AMap.OnCameraChangeListener) mContext);
                    }

                    @Override
                    public void onCancel() {

                    }
                });
            }
        }, 1000);
    }


    //初始化适配器
    private void initAdapter() {
        swipeLayout.setOnRefreshListener(this);
        swipeLayout.setColorSchemeColors(getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color),
                getResources().getColor(R.color.text_select_color));
        rv_list.setLayoutManager(new MyLinearLayoutManager(this));
        locationAddressAdapter = new LocationAddressAdapter();
        locationAddressAdapter.openLoadAnimation();
        locationAddressAdapter.setOnLoadMoreListener(this);
        rv_list.setAdapter(locationAddressAdapter);
    }

    private void setMovingMarker() {
        if (isMovingMarker)
            return;
        isMovingMarker = true;
        centerMarker.setIcon(movingDescriptor);
    }


    /**
     * POI信息查询结果回调方法
     */
    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        swipeLayout.setRefreshing(false);
        if (i == AMapException.CODE_AMAP_SUCCESS) {
            if (poiResult != null && poiResult.getQuery() != null) {// 搜索poi的结果
                if (poiResult.getQuery().equals(poiQuery)) {
                    List<PoiItem> poiItems = poiResult.getPois();
                    if (poiItems.size() == 0)
                        locationAddressAdapter.loadMoreEnd(true);
                    if (currentPage == 1) {
                        locationAddressAdapter.setNewData(poiItems);
                    } else {
                        locationAddressAdapter.addData(poiItems);
                        locationAddressAdapter.loadMoreComplete();
                    }
                }
            }
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }


    @Override
    public void onRegeocodeSearched(RegeocodeResult regeocodeResult, int i) {
        endAnim();
    }

    @Override
    public void onGeocodeSearched(GeocodeResult geocodeResult, int i) {

    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        if (centerMarker != null) {
            setMovingMarker();
        }

    }

    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        screenPoint = new LatLonPoint(cameraPosition.target.latitude,
                cameraPosition.target.longitude);
        animMarker();
        doSearchQuery();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mapView.onPause();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onRefresh() {
        locationAddressAdapter.setEnableLoadMore(false);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                currentPage = 1;
                locationAddressAdapter.getData().clear();
                doSearchQuery();
                locationAddressAdapter.setEnableLoadMore(true);
            }
        }, delayMillis);
    }

    @Override
    public void onLoadMoreRequested() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (isEnd == 1) {
                    locationAddressAdapter.loadMoreEnd(true);
                } else {
                    currentPage++;
                    doSearchQuery();
                }
            }
        }, delayMillis);
    }

    @Override
    public void onGetInputtips(List<Tip> list, int resCode) {
        if (resCode == AMapException.CODE_AMAP_SUCCESS) {// 正确返回
            listInput = list;
            List<String> listString = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                listString.add(list.get(i).getName());
            }
            ArrayAdapter<String> aAdapter = new ArrayAdapter<>(
                    getApplicationContext(),
                    R.layout.item_location_tips, R.id.online_user_list_item_textview, listString);
            et_search.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        } else {
            ShowToast.showShortToast(resCode);
        }
    }

    TextWatcher searchLocation = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String newText = s.toString().trim();
            if (!AMapUtil.IsEmptyOrNullString(newText)) {
                InputtipsQuery inputquery = new InputtipsQuery(newText, SPUtil.getUserLocation().getCityName());
                Inputtips inputTips = new Inputtips(SelLocationActivity.this, inputquery);
                inputTips.setInputtipsListener(SelLocationActivity.this);
                inputTips.requestInputtipsAsyn();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    };
}
